/**
 * 修改登录手机页面
 * author wim
 */
import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import '../base/Constant.dart';

class ChangePhonePage extends StatefulWidget {
  ChangePhonePage({Key key}) : super(key: key);

  _ChangePhonePageState createState() => _ChangePhonePageState();
}

class _ChangePhonePageState extends State<ChangePhonePage> {
  String token = "";
  String old_phone = "";
  String new_Phone = "";
  String new_code = "";
  String old_code = "";
  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;
  BlankToolBarModel barModel = BlankToolBarModel();
  Timer _countdownTimer_new;
  int _countdownNum_new = 59;
  String codeString_new = "获取验证码";
  int codeStatus_new = 1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value ?? "";
    });
    getString(PHONE).then((value) {
      setState(() {
        old_phone = value ?? "";
      });
    });
    barModel.outSideCallback = focusNodeChange;
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: new Scaffold(
        appBar: AppBar(
          title: Text(
            '更换手机号',
            style: TextStyle(color: black, fontSize: 18),
          ),
          backgroundColor: white,
          brightness: Brightness.light,
          elevation: 0.2,
          iconTheme: IconThemeData(color: black_99),
        ),
        body: BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: new SingleChildScrollView(
              child: new Container(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.all(15),
                      child: Text(
                        '当前登录手机账号:$old_phone',
                        style: TextStyle(color: mainColor, fontSize: 14),
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            width:
                                ScreenUtil.getInstance().setWidth(DP_200 + 10),
                            child: Text(
                              '原手机验证码',
                              style: TextStyle(fontSize: 16, color: black_99),
                            ),
                          ),
                          Expanded(
                            child: TextField(
                              style: TextStyle(fontSize: 16, color: black_99),
                              keyboardType: TextInputType.numberWithOptions(),
                              maxLines: 1,
                              minLines: 1,
                              cursorColor: mainColor,
                              onChanged: (value) {
                                old_code = value;
                              },
                              keyboardAppearance: Brightness.light,
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "输入验证码",
                                  border: InputBorder.none),
                            ),
                            flex: 3,
                          ),
                          new Container(
                            height: 25,
                            decoration: new BoxDecoration(
                                color: codeStatus == 1 ? mainColor : grey,
                                borderRadius: BorderRadius.circular(20.0)),
                            padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                            child: new FlatButton(
                              child: new Padding(
                                padding: EdgeInsets.all(0.0),
                                child: new Text(
                                  codeString,
                                  style: new TextStyle(
                                      color:
                                          codeStatus == 1 ? white : Colors.grey,
                                      fontSize: 14),
                                ),
                              ),
                              onPressed: () {
                                if (codeStatus == 0) {
                                  return;
                                }
                                showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (_) {
                                      return new NetLoadingDialog(
                                        loadingText: "获取中...",
                                        bgColor: Color.fromARGB(255, 0, 0, 0),
                                        requestCallBack: null,
                                        outsideDismiss: false,
                                      );
                                    });
                                getCodeOld();
                              },
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            width:
                                ScreenUtil.getInstance().setWidth(DP_200 + 10),
                            child: Text(
                              '新手机号码',
                              style: TextStyle(fontSize: 16, color: black_99),
                            ),
                          ),
                          Expanded(
                            child: TextField(
                              keyboardAppearance: Brightness.light,
                              style: TextStyle(fontSize: 16, color: black_99),
                              maxLines: 1,
                              onChanged: (value) {
                                new_Phone = value;
                              },
                              minLines: 1,
                              cursorColor: mainColor,
                              keyboardType: TextInputType.numberWithOptions(),
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "请输入新号码",
                                  border: InputBorder.none),
                            ),
                            flex: 2,
                          ),
                        ],
                      ),
                    ),
                    Container(
                      color: divideColor,
                      height: 1,
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            width:
                                ScreenUtil.getInstance().setWidth(DP_200 + 10),
                            child: Text(
                              '新手机验证码',
                              style: TextStyle(fontSize: 16, color: black_99),
                            ),
                          ),
                          Expanded(
                            child: TextField(
                              style: TextStyle(fontSize: 16, color: black_99),
                              maxLines: 1,
                              keyboardAppearance: Brightness.light,
                              keyboardType: TextInputType.numberWithOptions(),
                              minLines: 1,
                              cursorColor: mainColor,
                              onChanged: (value) {
                                new_code = value;
                              },
                              decoration: new InputDecoration(
                                  contentPadding: EdgeInsets.all(5),
                                  hintText: "输入验证码",
                                  border: InputBorder.none),
                            ),
                            flex: 3,
                          ),
                          new Container(
                            height: 25,
                            decoration: new BoxDecoration(
                                color: codeStatus_new == 1 ? mainColor : grey,
                                borderRadius: BorderRadius.circular(20.0)),
                            padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                            child: new FlatButton(
                              child: new Padding(
                                padding: EdgeInsets.all(0.0),
                                child: new Text(
                                  codeString_new,
                                  style: new TextStyle(
                                      color: codeStatus_new == 1
                                          ? white
                                          : Colors.grey,
                                      fontSize: 14),
                                ),
                              ),
                              onPressed: () {
                                if (codeStatus_new == 0) {
                                  return;
                                }
                                showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (_) {
                                      return new NetLoadingDialog(
                                        loadingText: "获取中...",
                                        bgColor: Color.fromARGB(255, 0, 0, 0),
                                        requestCallBack: null,
                                        outsideDismiss: false,
                                      );
                                    });
                                getCodeNew();
                              },
                            ),
                          )
                        ],
                      ),
                    ),
                    new Container(
                      width: double.infinity,
                      height: ScreenUtil.getInstance().setHeight(DP_80),
                      margin: EdgeInsets.fromLTRB(50, 30, 50, 0),
                      decoration: new BoxDecoration(
                          color:mainColor,
                          borderRadius: BorderRadius.circular(
                              ScreenUtil.getInstance().setHeight(DP_80))),
                      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                      child: new FlatButton(
                        child: new Padding(
                          padding: EdgeInsets.all(0.0),
                          child: new Text(
                            "确定提交",
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)),
                          ),
                        ),
                        onPressed: () {
                          changePhone();
                        },
                      ),
                    )
                  ],
                ),
              ),
            )),
      ),
    );
  }

  changePhone() async {
    if (old_code == "") {
      Fluttertoast.showToast(msg: "请输入旧手机验证码");
      return;
    }
    if (new_Phone == "") {
      Fluttertoast.showToast(msg: "请输入新手机号");
      return;
    }
    if (new_code == "") {
      Fluttertoast.showToast(msg: "请输入新手机验证码");
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['phone'] = new_Phone;
    map['code'] = new_code;
    map['old_code'] = old_code;
    map['sign_type'] = SignType.CHANGE_LOGIN_PHONE;
    Response<String> response =
        await HttpUtil().post(Api.CHANGE_PHONE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1) {
      saveString(TOKEN, "");
      Navigator.of(context).pop();
    }
  }

  getCodeOld() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.SEND_OLD_CODE;
    Response<String> response = await HttpUtil()
        .post(Api.SEND_CHANGE_OLD_PHONE_CODE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

  getCodeNew() async {
    if (new_Phone == "") {
      Fluttertoast.showToast(msg: "请输入新手机号");
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['phone'] = new_Phone;
    map['sign_type'] = SignType.SEND_NEW_CODE;
    Response<String> response =
        await HttpUtil().post(Api.SEND_CHANGE_PHONE_CODE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        codeStatus_new = 0;
        if (_countdownTimer_new != null) {
          return;
        }
        codeString_new = '${_countdownNum_new--}重新获取';
        _countdownTimer_new =
            new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum_new > 0) {
              codeStatus_new = 0;
              codeString_new = '${_countdownNum_new--}重新获取';
            } else {
              codeString_new = '获取验证码';
              codeStatus_new = 1;
              _countdownNum_new = 59;
              _countdownTimer_new.cancel();
              _countdownTimer_new = null;
            }
          });
        });
      });
    }
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    _countdownTimer_new?.cancel();
    _countdownTimer_new = null;
    barModel.removeFocusListeners();

    super.dispose();
  }
}
